package com.xyh.pool;


import org.apache.commons.pool.BasePoolableObjectFactory;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.StackObjectPool;

public class Pool {

    public static void main(String[] args) throws Exception {
        ObjectPool pool = new StackObjectPool(new UserFactory());
        User u = (User) pool.borrowObject(); // 从池中借出一个对象
        u.setName("me");
        u.sayHello();
        pool.returnObject(u); // 归还对象
        u.sayHello();
    }

    static class UserFactory extends BasePoolableObjectFactory {
        /**
         * 产生一个新对象
         */
        public Object makeObject() {
            return new User();
        }

        /**
         * 还原对象状态
         */
        public void passivateObject(Object obj) {
            User u = (User) obj;
            u.clear();
        }
    }

    static class User {
        String name;

        void setName(String name) {
            this.name = name;
        }

        void sayHello() {
            System.out.println("hello, " + name);
        }

        void clear() {
            name = "";
        }
    }
}
